from django import forms
from django.utils import timezone
from captcha.fields import CaptchaField
from .validators import validate_id_card
from .models import ExamRoom

class RegisterForm(forms.Form):
    phone = forms.CharField(max_length=20, label='手机号', help_text='请输入有效的手机号码')
    name = forms.CharField(max_length=50, label='姓名')
    password = forms.CharField(widget=forms.PasswordInput, label='密码', help_text='请输入至少8位的密码')
    confirm_password = forms.CharField(widget=forms.PasswordInput, label='确认密码', help_text='请再次输入密码')
    email = forms.EmailField(required=False, label='电子邮箱', help_text='选填，请输入有效的电子邮箱地址')
    gender = forms.ChoiceField(choices=[('M', '男'), ('F', '女'), ('O', '其他')], required=False, label='性别')
    organization = forms.CharField(max_length=100, required=False, label='所属机构', help_text='选填，请输入您所属的机构名称')
    id_card = forms.CharField(max_length=18, required=False, label='身份证号', help_text='选填，请输入18位身份证号码', validators=[validate_id_card])
    captcha = CaptchaField(label='验证码', help_text='请输入图片中的验证码')

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.error_messages = {'required': f'请输入{field.label}'}

class ExamRoomForm(forms.ModelForm):
    class Meta:
        model = ExamRoom
        fields = ['name', 'exam_type', 'start_time', 'duration', 'invigilators']
        help_texts = {
            'start_time': '考试开始时间必须至少在当前时间的2分钟之后',
        }

    def clean_start_time(self):
        start_time = self.cleaned_data.get('start_time')
        if start_time:
            now = timezone.now()
            min_start_time = now + timezone.timedelta(minutes=5)

            # 新创建的考试或状态为preparing的考试需要检查开始时间
            if not self.instance.pk or self.instance.status == 'preparing':
                if start_time < min_start_time:
                    raise forms.ValidationError('考试开始时间必须至少在当前时间的5分钟之后')
            # 对于所有考试，开始时间不能早于当前时间
            elif start_time < now:
                raise forms.ValidationError('考试开始时间不能早于当前时间')
        return start_time

class LoginForm(forms.Form):
    phone = forms.CharField(max_length=20, label='手机号', help_text='请输入您注册时使用的手机号')
    password = forms.CharField(widget=forms.PasswordInput, label='密码', help_text='请输入您的密码')
    captcha = CaptchaField(required=False, label='验证码', help_text='请输入图片中的验证码')  # 设置为非必需，根据登录失败次数决定是否验证

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        for field in self.fields.values():
            field.error_messages = {'required': f'请输入{field.label}'}